﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using SAP.WebServices;
using System.Collections;
using System.Globalization;
using System.Net;

namespace SAP
{
    public partial class Outgoing : System.Web.UI.Page
    {
        public static DataTable dtContents;
        public static DataTable dtHeader;
        private GeneralFunctions GF= new GeneralFunctions(HttpContext.Current.User.Identity.Name);
        private string DocType = "46";
        private string TblHeaderName = "OVPM";
        private string TblLineName = "VPM2";
        private string CurrentPageUrl = "/Banking/Outgoing.aspx";
        private string HeaderKeyName = "DocEntry";
        public static string KeepColumsContent = "";
    #region Functions
        protected void SetNavigatorURL(string CurrentKey)
        {
            GetDefault df = new GetDefault();
            DataSet nav = df.GetNextPreviousID(DocType, User.Identity.Name, TblHeaderName, HeaderKeyName, CurrentKey);
            if (nav != null)
            {
                this.linkFirst.NavigateUrl = CurrentPageUrl + "?order_id=" + nav.Tables[0].Rows[0]["Fir"].ToString(); ;
                this.linkNext.NavigateUrl = CurrentPageUrl + "?order_id=" + nav.Tables[0].Rows[0]["Nex"].ToString(); ;
                this.linkPrevious.NavigateUrl = CurrentPageUrl + "?order_id=" + nav.Tables[0].Rows[0]["Pre"].ToString(); ;
                this.linkLast.NavigateUrl = CurrentPageUrl + "?order_id=" + nav.Tables[0].Rows[0]["Las"].ToString(); ;
            }
            this.linkNew.NavigateUrl = CurrentPageUrl + "?order_id=";
        }
        protected void LoadData(String orderId, string NewDocType)
        {
            Transaction ts = new Transaction();
            DataSet returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, orderId, User.Identity.Name);
            DataTable dtHeader;

            if (returnDoc == null)
                orderId = "1";
            else
                dtHeader = returnDoc.Tables[0];

            returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, orderId, User.Identity.Name);

            if (returnDoc == null || returnDoc.Tables.Count<2 )
            {

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                    "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
                return;
            }

            dtHeader = returnDoc.Tables[0];
            dtContents = GF.ConvertDataTable_RemoveCols(returnDoc.Tables[1], "");
            DataRow dr = dtHeader.Rows[0];
            SetNavigatorURL(dr["DocEntry"].ToString());

            this.txtName.Text = dr["CardName"].ToString();
            this.txtVendor.Text = dr["CardCode"].ToString();
            lBP.NavigateUrl = "../BusinessPartner/BusinessPartnerMaster.aspx?cardcode=" + txtVendor.Text;
            hlJE.NavigateUrl = "../Financials/JournalEntry.aspx?order_id=" + dr["TransID"].ToString();
            MasterData masterDataWS = new MasterData();
            ddlContactPerson.DataSource = masterDataWS.GetContactPerson(txtVendor.Text, User.Identity.Name).Tables[0];
            ddlContactPerson.DataValueField = "Code";
            ddlContactPerson.DataTextField = "FirstName";
            ddlContactPerson.DataBind();

            this.txtNo.Text = dr["DocEntry"].ToString();
            CultureInfo ivC = new System.Globalization.CultureInfo("es-US");

            DateTime d = Convert.ToDateTime(dr["DocDate"], ivC);
            txtPostingDate.Text = String.Format("{0:MM/dd/yyyy}", d);

            d = Convert.ToDateTime(dr["TaxDate"], ivC);
            txtDocumentDate.Text = String.Format("{0:MM/dd/yyyy}", d);

            d = Convert.ToDateTime(dtHeader.Rows[0]["DocDueDate"], ivC);
            txtDueDate.Text = String.Format("{0:MM/dd/yyyy}", d);

            txtTotalPayment.Text = dtHeader.Rows[0]["DocTotal"].ToString();

            txtJournalRemark.Text = dr["JrnlMemo"].ToString();
            txtRemarks.Text = dr["Comments"].ToString();

            txtCashAccount.Text=dr["CashAcct"].ToString() ;
            txtCashApplied.Text = GF.FormatNumeric(dr["CashSum"].ToString(), "SumDec");
            txtTransferAccount.Text=dr["TrsfrAcct"].ToString();
            txtTransferApplied.Text = GF.FormatNumeric(dr["TrsfrSum"].ToString(), "SumDec");

            if (dr["PayNoDoc"].ToString()=="Y")
                ckPaymentOnAccount.Checked = true;
            else
                ckPaymentOnAccount.Checked = false;
            txtPaymentOnAccount.Text = GF.FormatNumeric(dr["NoDocSum"].ToString(), "SumDec");

            ddlTaxCode.SelectedValue = dr["VatGroup"].ToString();

            txtProject.Text = dr["PrjCode"].ToString();
            txtAddress.Text = dr["Address"].ToString();
            updateTableTotalPrice();

            txtTax.Text = GF.FormatNumeric(dr["vatSum"].ToString(), "SumDec");
            txtTotalPayment.Text = GF.FormatNumeric(dr["doctotal"].ToString(), "SumDec");

            txtTransID.Text = dr["TransID"].ToString();

            txtCounterRef.Text = dr["CounterRef"].ToString();
            this.lvContents.DataSource = dtContents;
            this.lvContents.DataBind();
        }       
        protected void ClearScreen()
        {
            dtHeader = new DataTable("ORCT");
            dtHeader.Columns.Add("CardCode");
            dtHeader.Columns.Add("CardName");
            dtHeader.Columns.Add("TaxDate");
            dtHeader.Columns.Add("DocDate");
            dtHeader.Columns.Add("DocDueDate");
            dtHeader.Columns.Add("Comments");
            dtHeader.Columns.Add("JrnlMemo");
            dtHeader.Columns.Add("Project");
            dtHeader.Columns.Add("CashAcct");
            dtHeader.Columns.Add("CashSum");
            dtHeader.Columns.Add("TrsfrAcct");
            dtHeader.Columns.Add("TrsfrSum");
            dtHeader.Columns.Add("U_UserID");
            dtHeader.Columns.Add("PayNoDoc");
            dtHeader.Columns.Add("NoDocSum");
            dtHeader.Columns.Add("VatGroup");
            dtHeader.Columns.Add("PrjCode");
            dtHeader.Columns.Add("Address");
            dtHeader.Columns.Add("CounterRef");
            dtHeader.Rows.Add();

            dtContents = new DataTable("RCT2");
            dtContents.Columns.Add("No");
            dtContents.Columns.Add("DocEntry");
            dtContents.Columns.Add("InvType");
            dtContents.Columns.Add("RefDate");
            dtContents.Columns.Add("DueDate");
            dtContents.Columns.Add("Overdue");
            dtContents.Columns.Add("BalDueDeb");
            dtContents.Columns.Add("SumApplied");
            dtContents.Columns.Add("DocLine");
            KeepColumsContent = "DocEntry;InvType;SumApplied;DocLine";

            CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
            txtPostingDate.Text.ToString(ci);

            txtAddress.Text = "";
            txtNo.Text = "";
            txtRemarks.Text = "";
            txtJournalRemark.Text = "";
            txtVendor.Text = "";
            txtName.Text = "";
            
            txtCashAccount.Text = "";
            txtTransferAccount.Text = "";
            txtCashApplied.Text = "";
            txtTransferApplied.Text = "";
            txtReference.Text = "";
            txtPaymentOnAccount.Text = "";
            ckPaymentOnAccount.Checked = false;
            txtTax.Text = "";
            txtTotalPayment.Text = "";
            txtCounterRef.Text = "";
            lvContents.DataSource = dtContents;
            lvContents.DataBind();

            SetNavigatorURL("0");
            SetScreenStatus("New");
        }
        private void SetControlsStatus(string asStatus)
        {
            switch (asStatus)
            {
                case "Add":
                     btnAdd.Enabled = false;
                    break;
                case "Edit":
                     btnAdd.Enabled=false;
                    break;
                case "Update":
                   btnAdd.Enabled = true;
                    break;
                case "Save":
                    btnAdd.Enabled  = true;
                    break;
            }
        }
        public String _collectData()
        {
            try
            {
                //Update table header
                DataRow dr = dtHeader.Rows[0];

                CultureInfo ivC = new System.Globalization.CultureInfo("es-US");

                dr["DocDate"] = Convert.ToDateTime(txtDueDate.Text, ivC).ToString("yyyyMMdd");
                dr["DocDueDate"] = Convert.ToDateTime(txtDueDate.Text, ivC).ToString("yyyyMMdd");
                dr["TaxDate"] = Convert.ToDateTime(txtDocumentDate.Text, ivC).ToString("yyyyMMdd");
                dr["Comments"] = txtRemarks.Text;
                dr["JrnlMemo"] = txtJournalRemark.Text;
                dr["CardCode"] = txtVendor.Text;
                dr["CardName"] = txtName.Text;
                dr["CashAcct"] =txtCashAccount.Text;
                dr["CashSum"] = GF.Object2Double((object)GF.ResetFormatNumeric(txtCashApplied.Text), "SumDec");
                dr["TrsfrAcct"] = txtTransferAccount.Text;
                dr["TrsfrSum"] = GF.Object2Double((object)GF.ResetFormatNumeric(txtTransferApplied.Text), "SumDec");
                dr["U_UserID"] = User.Identity.Name;

                if (ckPaymentOnAccount.Checked == true)
                {
                    dr["PayNoDoc"] = "Y";
                    dr["NoDocSum"] = GF.Object2Double((object)GF.ResetFormatNumeric(txtPaymentOnAccount.Text), "SumDec");
                }
                else
                {
                    dr["PayNoDoc"] = "N";
                    dr["NoDocSum"]=0;
                }
                
                dr["VatGroup"] = ddlTaxCode.SelectedItem.Value.ToString();
                dr["PrjCode"] = txtProject.Text;
                dr["Address"] = txtAddress.Text;
                dr["CounterRef"] = txtCounterRef.Text;
                int count = dtContents.Copy().Rows.Count ;
                for (int i = 0; i < count; i++)
                {
                    CheckBox cb = (CheckBox)lvContents.Items[i].FindControl("ckCheck");
                    if (cb.Checked == false)
                    {
                        DataRow[] dr1 = dtContents.Select("No='" + (i + 1).ToString() + "'");
                        if (dr1.Length==1)
                           dtContents.Rows.Remove(dr1[0]);
                    }
                }
                
                Array arrContentsCols = new string[] { "SumApplied" }; // Columns need to reset format numeric

                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");
                dtHeader.TableName = TblHeaderName;
                dtContents.TableName = TblLineName;
                ds.Tables.Add(dtHeader.Copy());
                dtContents = GF.ResetFormatNumeric(GF.ConvertDataTable_RemoveCols(dtContents, KeepColumsContent), arrContentsCols);
                ds.Tables.Add(dtContents.Copy());

                return objInfo.ToXMLStringFromDS(DocType, ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                    "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                              "Dialog.hideLoader();", true);
                return "";
            }
        }
        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnAdd.Visible = true;
                    btnselectall.Visible = true;
                    btnDeselect.Visible = true;
                    break;
                case "Update":
                    btnAdd.Visible = false;
                    btnselectall.Visible = false;
                    btnDeselect.Visible = false;
                    break;
                case "Close":
                    btnAdd.Visible = false;
                    btnselectall.Visible = false;
                    btnDeselect.Visible = false;
                    break;
            }
        }
        protected void updateTableTotalPrice()
        {
            //Array arrContentsCols = new string[] { "SumApplied","BalDueDeb" }; // Columns need to reset format numeric
           // dtContents = GF.ResetFormatNumeric(dtContents, arrContentsCols);
            CheckBox cb = new CheckBox();
            double orderTotal = 0.0;
            foreach (DataRow row in dtContents.Rows)
            {
                if (lvContents.Items.Count > 0)
                {
                    cb = (CheckBox)lvContents.Items[int.Parse(row["No"].ToString()) - 1].FindControl("ckCheck");
                }
                if (cb.ID!=null)
                {
                    if (cb.Checked == true)
                    {
                        double total = GF.Object2Double((object)GF.ResetFormatNumeric(row["SumApplied"].ToString()), "SumDec");
                        orderTotal += total;
                    }
                }
                //else
                //{
                //    double total = GF.Object2Double((object)GF.ResetFormatNumeric(row["SumApplied"].ToString()), "SumDec");
                //    orderTotal += total;
                //}
                updateRowTotalPrice(row);
            }
            if (cb.ID != null)
            {
                this.txtTax.Text = "0";
                this.txtTotalPayment.Text = GF.FormatNumeric(orderTotal.ToString(), "SumDec");
                txtCashApplied.Text = txtTotalPayment.Text;
            }
        }
        public void updateRowTotalPrice(DataRow row)
        {
            try
            {
                row["BalDueDeb"] = GF.FormatNumeric(row["BalDueDeb"].ToString(), "SumDec");
            }
            catch
            {
            }
            row["SumApplied"] = GF.FormatNumeric(row["SumApplied"].ToString(), "SumDec");
        }
        protected void LoadDefault()
        {
            this.txtPostingDate.Text = DateTime.Now.ToShortDateString();
            this.txtDueDate.Text = DateTime.Now.ToShortDateString();
            this.txtDocumentDate.Text = DateTime.Now.ToShortDateString();
            this.txtNo.Text = "";
            GetDefault gd = new GetDefault();
            DataTable dt = gd.GetDefaultPayment(User.Identity.Name, DateTime.Now.Year).Tables[0];
            txtCashAccount.Text = dt.Rows[0]["CashAcctCode"].ToString();
            txtTransferAccount.Text = dt.Rows[0]["TransferAcctCode"].ToString();
            lblCashAccountName.Text = dt.Rows[0]["CashAcctName"].ToString();
            lblTransferAccountName.Text = dt.Rows[0]["TransferAcctName"].ToString();

        }
    #endregion

    #region Event
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {                    
                    ClearScreen();
                    lvContents.DataSource = dtContents;
                    lvContents.DataBind();

                    MasterData md = new MasterData();
                    DataTable dt = md.GetCashFlowItem(User.Identity.Name).Tables[0];
                    dt.Rows.Add("-1","");
                    ddlCashFlow.DataSource = dt;
                    ddlCashFlow.DataTextField = "CFWName";
                    ddlCashFlow.DataValueField = "CFWId";
                    ddlCashFlow.DataBind();

                    dt = md.GetTaxGroup("O", User.Identity.Name).Tables[0];
                    dt.Rows.Add("", "");
                    ddlTaxCode.DataSource = dt;
                    ddlTaxCode.DataTextField = "Name";
                    ddlTaxCode.DataValueField = "Code";
                    ddlTaxCode.DataBind();
                    ddlTaxCode.SelectedValue = "";

                    String orderId = Request.QueryString["order_id"];
                    if (!String.IsNullOrEmpty(orderId))
                    {
                        LoadData(orderId, DocType);
                         SetScreenStatus("Close");
                    }
                    else
                    {
                        LoadDefault();
                        SetScreenStatus("New");
                    }                    
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
        }
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "EditBusinessPartnerCallBack":
                            BusinessPartner chosenPartner = Session["chosenPartner"] as BusinessPartner;
                            if (chosenPartner != null)
                            {
                                this.txtName.Text = chosenPartner.CardName;
                                this.txtVendor.Text = chosenPartner.CardCode;
                                lBP.NavigateUrl = "../BusinessPartner/BusinessPartnerMaster.aspx?cardcode=" + txtVendor.Text;

                                this.txtPostingDate.Text = DateTime.Now.ToShortDateString();
                                this.txtDueDate.Text = DateTime.Now.ToShortDateString();
                                this.txtDocumentDate.Text = DateTime.Now.ToShortDateString();
                                this.txtNo.Text = "";

                                lBP.NavigateUrl = "../BusinessPartner/BusinessPartnerMaster.aspx?cardcode=" + txtVendor.Text;
                                MasterData masterDataWS = new MasterData();
                                ddlContactPerson.DataSource = masterDataWS.GetContactPerson(txtVendor.Text, User.Identity.Name).Tables[0];
                                ddlContactPerson.DataValueField = "Code";
                                ddlContactPerson.DataTextField = "FirstName";
                                ddlContactPerson.DataBind();

                                Transaction trx = new Transaction();
                                dtContents = trx.GetDocumentForPayment(txtVendor.Text, DateTime.Parse( txtPostingDate.Text), User.Identity.Name).Tables[0];
                                dtContents = GF.ConvertDataTable_RemoveCols(dtContents, "");
                               
                                lvContents.DataSource = dtContents;
                                lvContents.DataBind();

                                updateTableTotalPrice();

                                lvContents.DataSource = dtContents;
                                lvContents.DataBind();
                                
                            }
                            break;
                        case "EditAccountCallBack":
                            AccountMasterData acct = Session["chosenAccount"] as AccountMasterData;
                            int itemNo = Int32.Parse(Session["chosenItemNo"] as String);
                            if (acct != null)
                            {
                                 switch(itemNo)
                                 {
                                     case 1: //cash account
                                         txtCashAccount.Text = acct.AcctCode;
                                         lblCashAccountName.Text = acct.AcctName;
                                         break;
                                     case 2: //Transfer account
                                         txtTransferAccount.Text = acct.AcctCode;
                                         lblTransferAccountName.Text = acct.AcctName;
                                         break;
                                     default:
                                         break;
                                 }
                            }
                            break;
                        case "EditProjectCallBack":
                            Project prj = Session["chosenProject"] as Project;
                            if (prj != null)
                            {
                                this.txtProject.Text = prj.PrjCode;
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
        }      
        protected void btnAdd_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtVendor.Text) == true)
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                       "Main.setMasterMessage('Missing Business Partner','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                  "Dialog.hideLoader();", true);
                    return;
                }

                if (string.IsNullOrEmpty(txtCashApplied.Text)==true & (string.IsNullOrEmpty(txtTransferApplied.Text)==true))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                       "Main.setMasterMessage('Confirmation Amount must be greater than zero','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                  "Dialog.hideLoader();", true);
                    return;
                }
                if (string.IsNullOrEmpty(txtCashAccount.Text) == true & (string.IsNullOrEmpty(txtTransferAccount.Text) == true))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                       "Main.setMasterMessage('Payment Account is not defined','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                  "Dialog.hideLoader();", true);
                    return;
                }
                String requestXML = _collectData();
                if (requestXML == "") return;

                SAP.WebServices.Transaction ts = new WebServices.Transaction();
                DataSet ds = ts.CreateMarketingDocument(requestXML, User.Identity.Name, DocType, "", false);
                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                       "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);

                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                  "Dialog.hideLoader();", true);
                SetControlsStatus("Save");
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
        }
        protected void UpdateCheckBox(object sender, EventArgs e)
        {
            updateTableTotalPrice();
        }
        protected void btnDeselect_Click(object sender, ImageClickEventArgs e)
        {
            foreach (DataRow row in dtContents.Rows)
            {
                CheckBox cb = (CheckBox)lvContents.Items[int.Parse(row["No"].ToString()) - 1].FindControl("ckCheck");
                cb.Checked = false;
            }
            this.txtTax.Text = "0";
            this.txtTotalPayment.Text = "0";
        }
        protected void btnselectall_Click(object sender, ImageClickEventArgs e)
        {
            double orderTotal = 0.0;
            foreach (DataRow row in dtContents.Rows)
            {
                CheckBox cb = (CheckBox)lvContents.Items[int.Parse(row["No"].ToString()) - 1].FindControl("ckCheck");
                cb.Checked = true;
                double total = GF.Object2Double((object)GF.ResetFormatNumeric(row["BalDueDeb"].ToString()), "SumDec");
                orderTotal += total;
            }
            this.txtTax.Text = "0";
            this.txtTotalPayment.Text = GF.FormatNumeric(orderTotal.ToString(), "SumDec");
        }
        protected void ckPaymentOnAccount_CheckedChanged(object sender, EventArgs e)
        {
            if (ckPaymentOnAccount.Checked == true)
            {
                txtPaymentOnAccount.Enabled = true;
            }
            else
            {
                txtPaymentOnAccount.Enabled = false;
                txtPaymentOnAccount.Text = "0";
            }
        }
        protected void lvContents_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            try
            {
                ListViewItem lvi = e.Item;
                switch (e.CommandName)
                {
                    case "CancelUpdate":
                        if (string.IsNullOrEmpty(((Label)lvi.FindControl("lblNo")).Text)) return;

                        Label lblNo1 = (Label)lvi.FindControl("lblNo");

                         foreach (DataRow row in dtContents.Rows)
                        {
                            if (row["No"].ToString().Equals(lblNo1.Text)) // update currentrow into data table
                            {
                                row["SumApplied"] = row["BalDueDeb"];
                                updateTableTotalPrice();
                                break;
                            }
                        }
                        this.lvContents.EditIndex = -1;
                        this.lvContents.DataSource = dtContents;
                        this.lvContents.DataBind();
                        break;
                    default: break;
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
        }
        protected void lvContents_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            Label lblNo = (Label)lvContents.Items[e.ItemIndex].FindControl("lblNo");

            foreach (DataRow row in dtContents.Rows)
            {
                if (row["No"].ToString().Equals(lblNo.Text)) // update currentrow into data table
                {
                    row["SumApplied"] = ((TextBox)lvContents.Items[e.ItemIndex].FindControl("txtSumApplied")).Text;
                    updateTableTotalPrice();
                    break;
                }
            }
            this.lvContents.EditIndex = -1;
            this.lvContents.DataSource = dtContents;
            this.lvContents.DataBind();
        }
    #endregion

       

        
        
    }
}